package main

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

// NetplanConfig 定义netplan配置结构
type NetplanConfig struct {
	Network struct {
		Version  int                    `yaml:"version"`
		Renderer string                 `yaml:"renderer"`
		Ethernets map[string]Interface `yaml:"ethernets"`
		Bridges   map[string]Bridge     `yaml:"bridges"`
		Wifis     map[string]Wifi       `yaml:"wifis"`
	} `yaml:"network"`
}

// Interface 定义以太网接口配置
type Interface struct {
	DHCP4      bool     `yaml:"dhcp4"`
	Addresses  []string `yaml:"addresses,omitempty"`
}

// Bridge 定义网桥配置
type Bridge struct {
	Interfaces   []string `yaml:"interfaces"`
	DHCP4        bool     `yaml:"dhcp4"`
	Addresses    []string `yaml:"addresses,omitempty"`
	Gateway4     string   `yaml:"gateway4,omitempty"`
	Nameservers  struct {
		Addresses []string `yaml:"addresses,omitempty"`
	} `yaml:"nameservers,omitempty"`
}

// Wifi 定义无线网络配置
type Wifi struct {
	DHCP4         bool                   `yaml:"dhcp4"`
	AccessPoints  map[string]AccessPoint `yaml:"access-points"`
}

// AccessPoint 定义无线接入点配置
type AccessPoint struct {
	Password string `yaml:"password"`
}

func main() {
	// 示例YAML数据
	yamlData := `
network:
  version: 2
  renderer: networkd
  ethernets:
    lan1:
      dhcp4: no
      addresses:
        - 192.168.1.2/24
    lan2:
      dhcp4: no
    lan3:
      dhcp4: no
    lan4:
      dhcp4: no
  bridges:
    br0:
      interfaces: [lan2,lan3,lan4]
      dhcp4: yes
      addresses: [192.168.2.1/24]
      gateway4: 192.168.1.2
      nameservers:
          addresses: [8.8.8.8,8.8.4.4]
  wifis:
    wlan0:
      dhcp4: yes
      access-points:
         "Gloyel":
             password: gloyel888888
`

	// 解析YAML
	var config NetplanConfig
	err := yaml.Unmarshal([]byte(yamlData), &config)
	if err != nil {
		fmt.Printf("解析YAML失败: %v\n", err)
		return
	}

	// 打印解析结果
	fmt.Printf("Netplan配置版本: %d\n", config.Network.Version)
	fmt.Printf("使用的渲染器: %s\n", config.Network.Renderer)
	
	// 打印以太网配置
	for name, eth := range config.Network.Ethernets {
		fmt.Printf("以太网接口 %s: DHCP4=%v, 地址=%v\n", name, eth.DHCP4, eth.Addresses)
	}
	
	// 打印网桥配置
	for name, br := range config.Network.Bridges {
		fmt.Printf("网桥 %s: 接口=%v, DHCP4=%v, 地址=%v, 网关=%v, DNS=%v\n",
			name, br.Interfaces, br.DHCP4, br.Addresses, br.Gateway4, br.Nameservers.Addresses)
	}
	
	// 打印无线配置
	for name, wifi := range config.Network.Wifis {
		for apName, ap := range wifi.AccessPoints {
			fmt.Printf("无线接口 %s: DHCP4=%v, 接入点=%s, 密码=%s\n",
				name, wifi.DHCP4, apName, ap.Password)
		}
	}
}